// gcc -Wall mmap.c -o ../../build/mmap -lrt

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <string.h>
void sys_error(const char *msg)
{
    perror(msg);
    exit(EXIT_FAILURE);
}
int main(int argc, char const *argv[])
{
    int m1 = shm_open("m1", O_CREAT | O_RDWR, 0644);
    if(m1 < 0)
        sys_error(" open mmap failed");
    pid_t pid;
    ftruncate(m1, 100);
    char *share = mmap(NULL, 100, PROT_READ|PROT_WRITE,MAP_SHARED, m1, 0);
    if(share == MAP_FAILED)
        sys_error("map failed");
    close(m1);
    pid = fork();
    if(pid == 0){
        strcpy(share, "great\n");
        printf("child %d finished\n",getpid());
    }
    else
    {
        sleep(1);
        printf("%d received %d's massage: %s\n",getpid(),pid,share);
        wait(NULL);
    }
    m1 = munmap(share, 100);
    if(m1 == -1)
        sys_error("unmap failed");
    shm_unlink("m1");
    return 0;
}
